//
//  WCBAddAdressTableViewController.m
//  WeChatBuniess
//
//  Created by TFAppleWork-Summer on 2017/12/15.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBAddAdressTableViewController.h"
#import "WCBAddAdressTableViewCell.h"
#import "WCBRegionTableViewController.h"
#import "WCBAdressModel.h"
#import "WCBAdressViewModel.h"
#import "WCBRegionModel.h"
#import "WCBDataHelper.h"
#import "WCASessionManager.h"
#import "WCBUtility.h"

static NSString *const kWCBAddAdressTableViewCellID = @"kWCBAddAdressTableViewCellID";

@interface WCBAddAdressTableViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;

@property (copy, nonatomic) NSString *contacts;
@property (copy, nonatomic) NSString *phoneNumber;
@property (copy, nonatomic) NSString *area;
@property (copy, nonatomic) NSString *address;
@property (assign, nonatomic) BOOL isDefault;

@property (copy, nonatomic) NSString *m_area;
@property (copy, nonatomic) NSString *m_city;
@property (copy, nonatomic) NSString *m_provice;

@end

@implementation WCBAddAdressTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.isEdit) {
        self.title = @"编辑收货地址";
        self.contacts = self.adressViewModel.model.contacts;
        self.phoneNumber = self.adressViewModel.model.contactsPhone;
        self.area = self.adressViewModel.adressString;
        self.address = self.adressViewModel.model.address;
        self.isDefault = [self.adressViewModel.model.isdefault isEqualToString:@"1"] ? YES : NO;
        self.m_area = self.adressViewModel.model.area;
        self.m_city = self.adressViewModel.model.city;
        self.m_provice = self.adressViewModel.model.prov;
    }
    else {
        self.title = @"新增收货地址";
    }
    
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[WCBAddAdressTableViewCell class] forCellReuseIdentifier:kWCBAddAdressTableViewCellID];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action: @selector(onRightNavClick:)];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"img_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backDidClick)];
}

#pragma mark - Actions
- (void)backDidClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private

/**
 弹框提示
 */
-(void)p_showAlertWithString:(NSString *)string{
    UIAlertController *alert  = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}


/**
 打开选择地区的界面
 */
-(void)p_openRegionSelectVC{
    
    WCBRegionTableViewController *regionVC = [[WCBRegionTableViewController alloc]init];
    regionVC.pid = 0;
    __weak WCBAddAdressTableViewController *weak_self = self;
    regionVC.completeBlock = ^(WCBRegionModel *regionModel) {
        NSArray *array = [[WCBDataHelper sharedHelper] getAdressArrayForRegionModel:regionModel];
        
        if (array.count == 2)
        {// 只有两级 （xx省 xx市）
            self.m_area = @"0";
            for (NSInteger i = 0; i < array.count; i++)
            {
                WCBRegionModel *regionModel = array[i];
                switch (i)
                {
                    case 0:
                        self.m_city = [@(regionModel.locationId) stringValue];
                        break;
                    case 1:
                        self.m_provice = [@(regionModel.locationId) stringValue];
                        break;
                    default:
                        break;
                }
            }
        }else{
            for (NSInteger i = 0; i < array.count; i++) {
                WCBRegionModel *regionModel = array[i];
                switch (i) {
                    case 0:
                        self.m_area = [@(regionModel.locationId) stringValue];
                        break;
                    case 1:
                        self.m_city = [@(regionModel.locationId) stringValue];
                        break;
                    case 2:
                        self.m_provice = [@(regionModel.locationId) stringValue];
                        break;
                    default:
                        break;
                }
            }
        }
        
        NSString *adressString = [[WCBDataHelper sharedHelper]getAdressForRegionMdoel:regionModel];
        self.area = adressString;
        [weak_self.navigationController popToViewController:self animated:YES];
        [weak_self.tableView reloadData];
        NSLog(@"%@",array);
    };
    [self.navigationController pushViewController:regionVC animated:YES];
}

#pragma mark - action
-(void)onRightNavClick:(UIBarButtonItem *)button{
    if (!self.contacts) {
        [self p_showAlertWithString:@"请输入收货人"];
        return;
    }
    if (!self.phoneNumber) {
        [self p_showAlertWithString:@"请输入手机号"];
        return;
    }
    if (!self.address) {
        [self p_showAlertWithString:@"请输入详细地址"];
        return;
    }
    if (!self.area) {
        [self p_showAlertWithString:@"请选择收货地区"];
        return;
    }
    
    if (![[WCBUtility share] isMobileNumber:self.phoneNumber]) {
        [self p_showAlertWithString:@"请输入正确的手机号"];
        return;
    }
   NSDictionary * param = @{@"address" : self.address,
                            @"area" : self.m_area,
                            @"city" : self.m_city,
                            @"contacts" : self.contacts,
                            @"contactsPhone" : self.phoneNumber,
                            @"prov" : self.m_provice,
                            @"def" :@(self.isDefault),
                            @"id" : self.adressViewModel.model.id ? self.adressViewModel.model.id:@""
                            };
//
    [WCASessionManager  POST:@"tfmobile/cartM/addAddress"
                  parameters:param
                     success:^(NSURLSessionDataTask *task, id responseObject) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                             if ([[responseObject objectForKey:@"status"] boolValue]) {
                                 if (self.saveCompleteBlock) {
                                     self.saveCompleteBlock(YES);
                                 }
                                 [self.navigationController popViewControllerAnimated:YES];
                             }
                             else{
                                 [self p_showAlertWithString:[responseObject objectForKey:@"info"]];
                             }
                             
                         });
                     }
                     failure:^(NSURLSessionDataTask *task, NSError *error) {
                         [self p_showAlertWithString:@"保存失败"];
                     }];
    
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return 4;
    }
    else{
        return 1;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WCBAddAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kWCBAddAdressTableViewCellID forIndexPath:indexPath];
    
    __weak WCBAddAdressTableViewController *_self = self;
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == 0 && row == 0) {
        [cell setUserName:self.contacts];
    }
    else if (section == 0 && row == 1) {
        [cell setPhoneNumber:self.phoneNumber];
    }
    else if (section == 0 && row == 2) {
        [cell setArea:self.area];
    }
    else if (section == 0 && row == 3) {
        [cell setAddress:self.address];
    }
    else if (section == 1 && row == 0) {
        [cell setDefaultAddress:self.isDefault];
    }
    
    cell.setDefaultDidClick = ^(BOOL isDefault) {
        _self.isDefault = isDefault;
    };
    
    cell.tapBlock = ^{
        [_self p_openRegionSelectVC];
    };
    
    cell.textChangedBlock = ^(NSString *text) {
        if (section == 0 && row == 0) {
            _self.contacts = text;
        }
        else if (section == 0 && row == 1) {
            _self.phoneNumber = text;
        }
        else if (section == 0 && row == 2) {
            _self.area = text;
        }
        else if (section == 0 && row == 3) {
            _self.address = text;
        }
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 && indexPath.row == 3 ) {
        return 120;
    }
    return 60;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.01;
    }
    else
    {
        return 15;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UITableView *)tableView{
    if (!_tableView ) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        NSLog(@"%@", NSStringFromUIEdgeInsets(_tableView.layoutMargins));
    }
    return _tableView;
}

-(WCBAdressViewModel *)adressViewModel{
    if (!_adressViewModel) {
        _adressViewModel = [[WCBAdressViewModel alloc]init];
       _adressViewModel.model = [[WCBAdressModel alloc]init];
    }
    return _adressViewModel;
}
- (void)dealloc {
    NSLog(@"\n**************\n%@\n*************\n",NSStringFromClass(self.class));
    
}

@end
